package com.jm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jm.common.util.entity.SelectCondition;
import com.jm.common.exception.ServiceException;
import com.jm.dao.EmployeeMapper;
import com.jm.pojo.Employee;
import com.jm.service.EmployeeService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 员工业务
 */
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeMapper, Employee> implements EmployeeService {
    /**
     * 检查用户名是否存在于数据库中
     *
     * @param username 需要被检查的用户名
     * @return 是否存在
     */
    @Override
    public boolean checkUsernameIsExists(String username) {
        if (username == null || "".equals(username)) throw new ServiceException("需要被检查的用户名为空,检查失败");
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(true, Employee::getUsername, username);
        List<Employee> list = list(qw);
        return !list.isEmpty();
    }

    /**
     * 根据用户名密码拿到对象
     * @return
     */
    @Override
    public Employee getLogin(String username, String password) {
//        判空
        if (username == null || username.length() == 0) throw new ServiceException("输入的用户名为空");
        if (password == null || password.length() == 0) throw new ServiceException("输入的密码为空");
//        构造条件
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(true, Employee::getUsername, username)
                .eq(true, Employee::getPassword, password);
        return getOne(qw);
    }

    /**
     * 条件分页查询
     */
    @Override
    public IPage<Employee> selectByPageCondition(SelectCondition condition) {
        Long currentPage = condition.getPage();
        Long pageSize = condition.getPageSize();
        if (currentPage == null || pageSize == null)
            throw new ServiceException("分页条件设置错误");
//        构造分页
        IPage<Employee> page = new Page<>(currentPage,pageSize);
//        构造查询条件
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(condition.getName() != null, Employee::getName, condition.getName());
//        进行查询
        page(page, qw);
        return page;
    }
}
